import 'dart:math';

import 'package:flutter/material.dart';

class CustomCircularProgressIndicator extends StatelessWidget {
  const CustomCircularProgressIndicator({
    this.backgroundColor = const Color(0x1AFFFFFF),
    this.valueColor = const Color(0xFFFFFFFF),
    this.strokeWidth = 5.0,
    this.value,
  }) : assert(value != null);
  final Color backgroundColor;
  final Color valueColor;
  final double strokeWidth;
  final double value;

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: const BoxConstraints(
        minHeight: 64.0,
      ),
      child: AspectRatio(
        aspectRatio: 1.0,
        child: CustomPaint(
          painter: _CustomCircularProgressIndicatorPainter(
            backgroundColor: backgroundColor,
            valueColor: valueColor,
            strokeWidth: strokeWidth,
            value: value,
          ),
        ),
      ),
    );
  }
}

class _CustomCircularProgressIndicatorPainter extends CustomPainter {
  const _CustomCircularProgressIndicatorPainter({
    this.backgroundColor,
    this.valueColor,
    this.value,
    this.strokeWidth,
  });

  final Color backgroundColor;
  final Color valueColor;
  final double value;
  final double strokeWidth;

  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeWidth = strokeWidth
      ..color = backgroundColor;

    final Rect trackRect = Offset.zero & size;
    final Rect drawRect =
        EdgeInsets.all(strokeWidth * 0.5).deflateRect(trackRect);
    canvas.drawCircle(drawRect.center, drawRect.width * 0.5, paint);

    paint
      ..isAntiAlias = true
      ..color = valueColor;

    canvas.drawArc(drawRect, pi * -0.5, value * pi * 2, false, paint);
  }

  @override
  bool shouldRepaint(_CustomCircularProgressIndicatorPainter oldPainter) {
    return oldPainter.backgroundColor != backgroundColor ||
        oldPainter.valueColor != valueColor ||
        oldPainter.value != value;
  }
}
